'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 邮件
 * @author sundbcn@gmail.com (sun debing)
 */

var moment = require('moment');
var mongoose = require('mongoose');
var _ = require('lodash');
var dataApi = require('../libs/dataApi');
var constantUtil = require('../util/constantUtil');
var mailItemSchema = require('./mail/mailItemSchema');
var mailMgr = require('../mgr/mailMgr');

///////////////////////////////////////////////////////////
/**
 * 邮件
 */
var mailSchema = new mongoose.Schema({
    // 角色id
    role_id: {
        type: Number,
        required: true,
        unique: true,
        index: true
    },

    // 邮件列表
    mail_list: [mailItemSchema],

    // 邮件后台ＩＤ记录
    email_guid: {
        type: [Number]
    },

    // 自增id
    max_id: {
        type: Number,
        default: 10000
    }
});

mailSchema.pre('save', function (next) {
    this.increment();
    if (!this.isNew && !!this.isModified()) {
        this.pushModify();
    }
    next();
});

/**
 * 邮件列表
 */
mailSchema.methods.addEmailGuid = function (email_guid) {
    var status = _.indexOf(this.email_guid, email_guid) == -1;
    if (!!status) {
        this.email_guid.push(email_guid);
    }
};

/**
 * 邮件列表
 */
mailSchema.methods.isEmailGuid = function (email_guid) {
    var status = _.indexOf(this.email_guid, email_guid) == -1;
    if (!!status) {
        return true;
    } else {
        return false;
    }
};

/**
 * 邮件列表
 */
mailSchema.methods.getMailList = function () {
    return this.mail_list;
};

/**
 * 添加邮件
 */
/*jshint maxparams: 10 */
mailSchema.methods.addMail = function (mail_title, mail_content, mail_reward_list, module_type, operation_type, reserve_int_val, reserve_str_val) {
    var attach_list = [];
    _.each(mail_reward_list, function (reward_list) {
        attach_list.push(reward_list);
    });

    var mail_item = {
        mail_id: this.genId(),
        title: mail_title,
        content: mail_content,
        attach_list: attach_list
    };
    if (!!module_type) {
        mail_item.module_type = module_type;
    }
    if (!!operation_type) {
        mail_item.operation_type = operation_type;
    }
    if (!!reserve_int_val) {
        mail_item.reserve_int_val = reserve_int_val;
    }
    if (!!reserve_str_val) {
        mail_item.reserve_str_val = reserve_str_val;
    }

    this.mail_list.push(mail_item);
};

/**
 * 获取邮件
 */
mailSchema.methods.getMailById = function (mail_id) {
    for (var i = this.mail_list.length - 1; i >= 0; i--) {
        var mail_item = this.mail_list[i];
        if (mail_item.mail_id == mail_id) {
            mail_item.setReadStatus();
            return mail_item;
        }
    }
    return null;
};

/**
 * 删除邮件
 */
mailSchema.methods.deleteMail = function (mail_id) {
    for (var i = this.mail_list.length - 1; i >= 0; i--) {
        var mail_item = this.mail_list[i];
        if (mail_item.mail_id == mail_id &&
            mail_item.getReadStatus() &&
            mail_item.getAttach().length === 0
        ) {
            mail_item.remove();
            this.remove_mail_list = this.remove_mail_list || [];
            this.remove_mail_list.push({
                mail_id: mail_id,
                del: 1
            });
        }
    }
};

/**
 * 获取邮件奖励
 */
mailSchema.methods.getMailReward = function (mail_id) {
    var mail = this.getMailById(mail_id);

    // 邮件是否存在
    if (!mail) {
        return null;
    }

    var attach_list = mail.getAttach();
    if (attach_list.length === 0) {
        return null;
    }
    mail.deleteAttach();
    return attach_list;
};

/**
 * 获取所有邮件奖励
 */
mailSchema.methods.getAllMailReward = function () {
    var mail_list = this.getMailList();
    var reward_list = [];

    for (var i = mail_list.length - 1; i >= 0; i--) {
        var mail_item = mail_list[i];
        if (!mail_item) {
            continue;
        }

        var attach_list = mail_item.getAttach();
        if (attach_list.length === 0) {
            continue;
        }

        mail_item.setReadStatus();
        for (var j = attach_list.length - 1; j >= 0; j--) {
            var attach_item = attach_list[j];
            reward_list.push({
                reward_type: attach_item.reward_type,
                reward_value: attach_item.reward_value,
                reward_num: attach_item.reward_num,
                reward: attach_item.reward
            });
        }
        mail_item.deleteAttach();
        this.deleteMail(mail_item.mail_id);
    }
    return reward_list;
};

mailSchema.methods.genId = function () {
    this.max_id++;
    return this.max_id;
};

/**
 
 * 获取修改
 */
mailSchema.methods.getLastChange = function () {
    var mail_list = [];
    _.each(this.mail_list, function (mail_item) {
        if (!!mail_item.isModified()) {
            mail_list.push(mail_item);
        }
    });

    _.each(this.remove_mail_list, function (remove_mail_item) {
        mail_list.push(remove_mail_item);
    });

    return {
        mail_list: mail_list
    };
};

/**
 * 推送给用户
 * @return {[type]} [description]
 */
mailSchema.methods.push = function () {
    mailMgr.sendMailChanged(
        this.role_id,
        this.toJSON(),
        function (err, fails) {
            if (err) {
                console.error('send mail message error: %j, fail ids: %j', err, fails);
                return;
            }
        }
    );
};

mailSchema.methods.pushModify = function () {
    mailMgr.sendMailChanged(
        this.role_id,
        this.getLastChange(),
        function (err, fails) {
            if (err) {
                console.error('send mail message error: %j, fail ids: %j', err, fails);
                return;
            }
        }
    );
};

if (!mailSchema.options.toJSON) {
    mailSchema.options.toJSON = {};
}

/* jshint unused:false */
mailSchema.options.toJSON.transform = function (doc, ret) {
    delete ret._id;
    delete ret.__v;
};

mongoose.model('Mail', mailSchema);
